package com.fingard.dsp.bank.directbank.srcb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.*;

public class SRCB01SinglePay extends SRCB01Base implements ISinglePay {

    private static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    private static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=?;";

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        // 返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        retAts.writeStart();
        RetAtsSglDetail retDetail = new RetAtsSglDetail();

        try {

            Connection conn = FGBiz.getLocalDbConn();
            //请求登陆
            String[] loginResult = login();
            loginResult[0] = "";
            if (loginResult[0].length() != 0) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(loginResult[1]);
            }

            List<String[]> paramStep1 = new ArrayList<String[]>();
            //新建发送银行报文
            XmlTextWriter xmlWriterStep1 = new XmlTextWriter();
            String transCode = "0010";
            String packetId = Format.Date8Format.format(new Date()) + p_req1908.singleDetail.askNumber;
            writeCommonHeader(xmlWriterStep1, transCode, packetId);

            if (p_req1908.singleDetail.sameBnk.equals("0")) {    //跨行转账
                transCode = "0011";
                paramStep1.add(new String[]{"PayeeAcctBank", p_req1908.singleDetail.recBankName});      //收款开户行
                paramStep1.add(new String[]{"PayeeAcctName", p_req1908.singleDetail.recName});          //收款人全称
                paramStep1.add(new String[]{"PayeeAcctBankCode", p_req1908.singleDetail.recBankCode});  //收款开户行联行号
                //如果指令是190805（单笔），198805（批量），就走网银互联IsEBankPay，如果符合，则也走网银互联，IsEBankPay，如果符合，则也走网银互联
                if (p_req1908.reqHeader.commandCode.equals("190805") || p_req1908.reqHeader.commandCode.equals("198805")){
                    paramStep1.add(new String[]{"PayRouter", "3"}); //1非农信银跨行转账 2农信银转账 3网银互联
                } else {
                    paramStep1.add(new String[]{"PayRouter", "1"}); //1非农信银跨行转账 2农信银转账 3网银互联
                }
            }


            paramStep1.add(new String[]{"PayerAcctNo", p_req1908.singleDetail.payAct});     //付款人账号
            paramStep1.add(new String[]{"PayeeAcctNo", p_req1908.singleDetail.recAct});     //收款人账号
            paramStep1.add(new String[]{"PayeeAcctName", p_req1908.singleDetail.recName});  //收款人全称
            paramStep1.add(new String[]{"PayCurr", getBankConfig().getMapValueByKey("currencyMapping", p_req1908.singleDetail.payCur)});  //币种
            paramStep1.add(new String[]{"PayAmount", p_req1908.singleDetail.payAmount});    //金额
            paramStep1.add(new String[]{"PayUsage", p_req1908.singleDetail.purpose + "+" + p_req1908.singleDetail.abstractATS});    //付款用途

            writeBodyParams(xmlWriterStep1, paramStep1);

            String packet_id = xmlWriterStep1.getContentBetweenTag("packet_id");
            //记录ats支付流水号对应的银行支付流水号，供查询状态接口使用
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req1908.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1908.singleDetail.askNumber, packet_id});
            WriteBankLogStep2(xmlWriterStep1.toXmlString());
            String[] result = sendToBank(xmlWriterStep1.toXmlString());
            if (result[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(result[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/response/head/ret_code");
                    if ("000000".equals(tmpRetCode)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = tmpBkReader.getFirstText("/response/body/bank_remark");
                        retDetail.transState = tmpBkReader.getFirstText("/response/body/pay_status");
                        retDetail.payInfoCode = retDetail.transState;
                        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpBkReader.getFirstText("/response/head/err_msg");
                    }
                } else {
                    WriteBankLogLn("步骤一发送成功，银行返回报文解析失败，报文内容为：" + result[1]);
                    retDetail.respCode = "-1";
                    retDetail.respInfo = result[1];
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = result[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            WriteBankLogLn(e);
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();

        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            Connection conn = FGBiz.getLocalDbConn();
            String[] loginResult = login();
            if (loginResult[0].length() != 0) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(loginResult[1]);
            }

            //新建发送银行报文
            XmlTextWriter xmlWriterStep1 = new XmlTextWriter();
            String transCode = getBankConfig().getMapValueByKey("transCode", "1944");
            String packetId = Format.Date8Format.format(new Date()) + p_req1944.askNumber;
            writeCommonHeader(xmlWriterStep1, transCode, packetId);
            Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1944.askNumber});
            String entReqSeqNo;
            if (selMap.size() > 0) {
                entReqSeqNo = selMap.get("BANKREQSEQID").toString();
            } else {
                retAts.writeStart();
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("没有请求流水和银行请求流水映射关系");
                retAts.writeEnd();
                return retAts;
            }

            List<String[]> paramStep1 = new ArrayList<String[]>();
            paramStep1.add(new String[]{"EntReqSeqNo", entReqSeqNo});   //企业交易请求流水号
            writeBodyParams(xmlWriterStep1, paramStep1);
            String[] result = sendToBank(xmlWriterStep1.toXmlString());
            if (result[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(result[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/response/head/ret_code");
                    if ("000000".equals(tmpRetCode)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = tmpBkReader.getFirstText("/response/body/bank_remark");
                        retDetail.transState = tmpBkReader.getFirstText("/response/body/pay_status");
                        retDetail.payInfoCode = retDetail.transState;
                        retDetail.reqSeqID = p_req1944.askNumber;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpBkReader.getFirstText("/response/head/err_msg");
                    }
                } else {
                    WriteBankLogLn("步骤一发送成功，银行返回报文解析失败，报文内容为：" + result[1]);
                    retDetail.respCode = "-1";
                    retDetail.respInfo = result[1];
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = result[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
